# coding=utf-8
"""
自动更新合并host文件
Filename: updateHosts.py
usage: python updateHosts.py
version: 14.2.22
"""
import urllib
import re,sys,os,time,platform
import ConfigParser

ip='127.0.0.1'
#脚本路径
script_path=sys.argv[0]

#脚本所在目录
script_dir=os.path.dirname(script_path)

#屏蔽文件目录
hostsblock_dir=os.path.realpath(script_dir+os.sep+'hosts.block')

#合并文件目录
hosts_dir=os.path.realpath(script_dir+os.sep+'hosts')

#白名单
white_file=os.path.join(script_dir,'whitehost.txt')

#配置文件
if len(sys.argv)==2:
    config_file=sys.argv[1]
else:#use default test config file
    config_file='config.ini'
    
if os.path.isabs(config_file)==False:#若是相对路径，则转化为绝对的
    config_file=os.path.realpath(script_dir+os.sep+config_file)
    
hosts_paths={'Windows'	: r'C:\WINDOWS\system32\drivers\etc\hosts',
			'Linux'		: '/etc/hosts'}
def get_files(_dir):
	_list=[]	
	for root, dirs, files in os.walk(_dir, topdown=False):
		for name in files:
			_file= os.path.join(root, name)
			_list.append(_file)
	return _list

def get_lines(file):
    _lines=['#host.block/'+os.path.basename(file)]
    _h=open(file,'r')
    for line in _h.readlines():
        line=line.strip()
        if in_white_list(line):
            continue
        if line!='':
            _lines.append(ip+'\t'+line)
    
    _h.close();
    return _lines

def get_white_list(file):
    _list=[]
    if os.path.isfile(file)==False:
        return _list
    f=open(file,'r')
    for line in f.readlines():
        line=line.strip()
        if line!='':
            _list.append(line)
    f.close();
    return _list

def in_white_list(host):
    global white_list
    return host in white_list

print(config_file)
host_web=''  
if os.path.isfile(config_file):    
    cf = ConfigParser.ConfigParser()
    try:
        cf.read(config_file)
    except Exception as e:
        print('Parse config file failed')
        print(e)
    if cf.has_option('host', 'web_host'):
            host_web    =cf.get('host','web_host')     

#原样copy hosts目录中的文件
copy_str=""
for file in get_files(hosts_dir):
    copy_str=copy_str+'#host/'+os.path.basename(file)+'\n';
    copy_str=copy_str+open(file,'r').read(1024*1024)
    copy_str=copy_str+'\n\n'
if host_web!='':
    print(host_web)
    try:
        _c= urllib.urlopen(host_web).read()
        copy_str=copy_str+'#web_host:'+host_web+'\n'+_c+'\n\n';
    except Exception as e:
        print('get web hosts file failed')
white_list=get_white_list(white_file)
#print white_list


new_hosts=[]
for file in get_files(hostsblock_dir):
    print(os.path.basename(file))
    new_hosts.extend(get_lines(file))
    new_hosts.extend('\n\n')


start_notice='\n#以下内容自动生成，修改后会自动覆盖\n\n'
_content=start_notice+copy_str+"\n".join(new_hosts)


start='#----ksc_start-----'
end  ='#----ksc_end-----'
_content=start+'\n'+_content+'\n'+end
hosts_path=hosts_paths[platform.system()]
hosts_out=hosts_path #r'D:\work\hosts\result.txt'


hosts_file= open(hosts_path,'r+')

lines = hosts_file.readlines()

need_insert= True
hosts_list=[]

is_filter=False
for i in lines:
    if(i.find('ksc_start')!=-1):
        hosts_list.append(_content+'\n')
        need_insert=False
        is_filter=True
    else:
        if is_filter:
            if(i.find('ksc_end')!=-1):#结束标记
                is_filter=True;
        else:
            hosts_list.append(i)
	
if need_insert:
    
    hosts_list.append('\n'+_content )
 
hosts_file.close()
try:
    hosts_file= open(hosts_out,'w')
    hosts_file.write(''.join(hosts_list));
    hosts_file.close()
    print("success")
except Exception as e:
    print(e)
    
time.sleep(2)
